<!--  -->
<template>
  <el-row :gutter="30" :style="{ marginTop: '20px' }">
    <!-- 左边栏 -->
    <el-col class="hidden-md-and-down" :span="6">
      <el-avatar
        v-if="userInfo.avatar != null"
        class="userAvatar"
        :src="userInfo.avatar"
        :size="100"
      ></el-avatar>
      <el-avatar
        v-if="userInfo.avatar == null"
        class="userAvatar"
        icon="el-icon-user-solid"
        :size="100"
      ></el-avatar>

      <!-- 用户名 -->
      <h1>{{ userInfo.username }}</h1>

      <el-divider></el-divider>

      <el-menu default-active="{ menuIndex }" @select="userPageSelect">
        <el-menu-item index="1">
          <span slot="title">我的主页</span>
        </el-menu-item>
        <el-menu-item index="2">
          <span slot="title">我的关注</span>
        </el-menu-item>
        <el-menu-item index="3">
          <span slot="title">修改密码</span>
        </el-menu-item>
      </el-menu>
    </el-col>

    <el-col class="user-content" :span="17" :xs="24" :sm="24" :md="24" :lg="17">
      <!-- 账号信息 -->
      <div v-if="showUserInfo">
        <h2 style="text-align: center">账号信息</h2>

        <el-form
          :model="userInfoForm"
          label-width="80px"
          style="padding: 0 100px"
        >
          <el-divider></el-divider>
          <el-form-item label="头像" style="height: 148px">
            <el-upload
              action="http://gulimall-yangrong.oss-cn-shanghai.aliyuncs.com"
              list-type="picture-card"
              ref="uploadImage"
              :data="dataObj"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :auto-upload="false"
              :on-preview="handlePictureCardPreview"
              :limit="1"
              :on-change="handleChange"
              :on-remove="handleRemove"
              accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .GIF, .PNG"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="userInfoForm.nickname"></el-input>
          </el-form-item>

          <el-divider></el-divider>
          <el-form-item label-width="0" style="text-align: center">
            <el-button type="primary" @click="saveUserInfo">更新资料</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 我的关注 -->
      <div v-if="showUserFocus">
        <h2 style="text-align: center">我的关注</h2>
        <el-divider></el-divider>
      </div>

      <!-- 修改密码 -->
      <div v-if="showChangePass">
        <h2 style="text-align: center">修改密码</h2>
        <el-divider></el-divider>
      </div>
    </el-col>
  </el-row>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { policy } from "@/components/upload/policy";
import { getUUID } from "@/utils";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      imageUrl: "",
      menuIndex: "1",
      userInfo: {},
      showUserInfo: false,
      showUserFocus: false,
      showChangePass: false,
      userInfoForm: {
        username: "",
        imageUrl: "",
        nickname: "",
      },
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    userPageSelect(key, keyPath) {
      if (key == 1) {
        this.showUserInfo = true;
        this.showUserFocus = false;
        this.showChangePass = false;
      } else if (key == 2) {
        this.showUserInfo = false;
        this.showUserFocus = true;
        this.showChangePass = false;
      } else if (key == 3) {
        this.showUserInfo = false;
        this.showUserFocus = false;
        this.showChangePass = true;
      }
    },
    saveUserInfo() {
      this.$refs.uploadImage.submit();
    },
    beforeUpload(file) {
      console.log(file);
      let _self = this;
      return new Promise((resolve, reject) => {
        policy()
          .then((response) => {
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key =
              response.data.dir +
              getUUID() +
              "." +
              file.type.substring(file.type.lastIndexOf("/") + 1);
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            _self.userInfoForm.imageUrl =
              _self.dataObj.host + "/" + _self.dataObj.key;
            resolve(true);
          })
          .catch((err) => {
            reject(false);
          });
      });
    },
    handleUploadSuccess(res, file, fileList) {
      // 文章封面图上传成功后进行文章保存操作，否则无法取到封面图远程链接
      this.$http({
        url: this.$http.adornUrl("/user/updateUserInfo"),
        method: "post",
        params: this.$http.adornParams({
          username: this.userInfoForm.username,
          nickname: this.userInfoForm.nickname,
          image: this.userInfoForm.imageUrl,
        }),
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            message: "个人信息更新成功！",
            type: "success",
          });
        }
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleChange(file, fileList) {
      // 限制上传1张封面图片，添加1张图片胡隐藏添加区域
      this.$refs.uploadImage.$children[1].$el.style.display = "none";
    },
    handleRemove(file, fileList) {
      // 限制上传1张封面图片，移除已添加的图片时，恢复添加区域显示状态
      this.$refs.uploadImage.$children[1].$el.style.display = "inline-block";
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let _this = this;
    _this.menuIndex = _this.$route.query.menuIndex;
    if (_this.menuIndex == 1) {
      this.showUserInfo = true;
      this.showUserFocus = false;
      this.showChangePass = false;
    } else if (_this.menuIndex == 2) {
      this.showUserInfo = false;
      this.showUserFocus = true;
      this.showChangePass = false;
    } else if (_this.menuIndex == 3) {
      this.showUserInfo = false;
      this.showUserFocus = false;
      this.showChangePass = true;
    }
    // 判断用户数据是否存在
    var userJsonStr = sessionStorage.getItem("user");
    if (userJsonStr != null) {
      _this.userInfo = JSON.parse(userJsonStr);
      _this.imageUrl = _this.userInfo.avatar;
      _this.userInfoForm.nickname = _this.userInfo.nickname;
      _this.userInfoForm.username = _this.userInfo.username;
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.hidden-md-and-down {
  background-color: white;
  border-radius: 8px;
  margin-right: 20px;
}

.hidden-md-and-down span {
  display: block;
  margin: 10px auto;
}

.hidden-md-and-down h1 {
  text-align: center;
}

.hidden-md-and-down .el-menu {
  border-right: 0;
  bottom: 20px;
}

.user-content {
  background-color: white;
  border-radius: 8px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>